class Admins::DangansController < ApplicationController

  require 'httpclient'

  def index

     t = Time.now.at_end_of_day.strftime("%Y-%m-%d %H:%M:%S")
    t1 = Time.mktime(Time.now.year,1,1).beginning_of_day.strftime("%Y-%m-%d %H:%M:%S")
   
    
    session[:news_begin] = params[:news_begin] ? params[:news_begin].to_date.beginning_of_day.strftime("%Y-%m-%d %H:%M:%S") : t1
    session[:news_end] = params[:news_end] ? params[:news_end].to_date.at_end_of_day.strftime("%Y-%m-%d %H:%M:%S") : t
    
    

  end

  def guidang
     t = Time.now.at_end_of_day.strftime("%Y-%m-%d %H:%M:%S")
    t1 = Time.mktime(Time.now.year,1,1).beginning_of_day.strftime("%Y-%m-%d %H:%M:%S")
   
    
    session[:news_begin] = params[:news_begin] ? params[:news_begin].to_date.beginning_of_day.strftime("%Y-%m-%d %H:%M:%S") : t1
    session[:news_end] = params[:news_end] ? params[:news_end].to_date.at_end_of_day.strftime("%Y-%m-%d %H:%M:%S") : t

    @news = News.where("pubtime >='"+session[:news_begin] +"' and pubtime <= '"+session[:news_end]+"' and \"check\" =2" )
    @news.each do |xw|
      writer('http://172.20.7.111//news/'+xw.id.to_s,xw.id.to_s+'.html')
      sleep 1
    end
    # writer('http://news.ecust.edu.cn/news/35353?important=0','35353.html')
    redirect_to '/admins/dangans'
  end

  def writer(url,name)
    root_path = Rails.root.to_s
    path_zip = "#{root_path}/public/file#{Date.today.year}"

    file1=File.new(path_zip+"/"+name, 'w+')
    client = HTTPClient.new

    begin
      client.get_content(url) do |chunk|
        file1<<chunk
      end
      sleep 1
      if File.size(file1) <5000
        writer(url,name)
      end
        
    rescue Exception  => e
      p e.message;
      writer(url,name)
    end
  end

end
